package com.qianniu.napi.admin.web.goods.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-23
 */
@RestController
public class GoodsCategoryController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsCategoryController.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsCategoryService goodscategoryService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IStoreService storeService;

    /*
     * 单机构商家版目录查询接口
     * showCategory:是否展示二级子目录
     */
    @RequestMapping("/api/goods/category/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "cid", required = false) int cid,
                      @RequestParam(value = "sid", required = false) Long sid,
                      @RequestParam(value = "type", required = false) String type,
                      @RequestParam(value = "showCategory", required = false) Boolean showCategory) {

        Jinfo json = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig mc = redisService.getMconfig();

        // 商家类目少 全部缓存到redis
        String rkey = Constants.REDIS_CATEGORY_LIST + mpid + "_" + cid;
        logger.debug("========rkey=" + rkey);
        List<GoodsCategory> bucket = redisService.get(rkey);
        if (bucket != null && bucket.size() > 0) {
            logger.debug("========rkey value=" + JSON.toJSONString(bucket));
            json.setInfo(bucket);
            return json;
        }

        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", mpid);
        wrapper.eq("state", 1);
        if(!Strings.isNullOrEmpty(type)) wrapper.eq("type", type);

        if (sid != null && sid.longValue() > 0) wrapper.eq("sid", sid);
        if (cid > 0) wrapper.eq("pid", cid);
        else wrapper.isNull("pid");
        wrapper.orderBy("paixu", true);

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);
        if (showCategory != null && !showCategory) {
            json.setInfo(list);
            return json;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        Wrapper<GoodsCategory> cwrapper = new EntityWrapper<GoodsCategory>();
        for (GoodsCategory item : list) {
            if (item.getHasChild() == 1) {
                cwrapper = new EntityWrapper<GoodsCategory>();
                cwrapper.eq("mpid", mpid);
                cwrapper.eq("pid", item.getId());
                cwrapper.orderBy("paixu", true);
                item.setChilds(goodscategoryService.selectList(cwrapper));
            } else {
                map.clear();
                map.put("cid", item.getId());
                map.put("skip", 0);
                map.put("limit", 6);
                item.setGoods(goodsService.getGoodsByMap(map));
            }
        }
        json.setInfo(list);
        if (cid == 0 && sid != null && sid.longValue() > 0) {
            json.setExtra(storeService.selectOne(new EntityWrapper<Store>()
                    .setSqlSelect("id,name,jianchen,pic,thumb,phone,wxno,qisongfee,peisongfee")
                    .eq("id", sid)));
        }
        if (mc.isCached()) redisService.set(rkey, bucket);// 商家类目少 全部缓存到redis
        return json;
    }

    /*
     * 单机构商家版目录查询接口
     * showCategory:是否展示二级子目录
     */
    @RequestMapping("/api/goods/category/list3")
    @ResponseBody
    public Jinfo list3(@RequestParam(value = "cid", required = false) int cid,
                      @RequestParam(value = "sid", required = false) Long sid,
                      @RequestParam(value = "type", required = false) String type,
                      @RequestParam(value = "showCategory", required = false) Boolean showCategory) {

        Jinfo json = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig mc = redisService.getMconfig();

        // 商家类目少 全部缓存到redis
        String rkey = Constants.REDIS_CATEGORY_LIST + mpid + "_" + cid;
        logger.debug("========rkey=" + rkey);
        List<GoodsCategory> bucket = redisService.get(rkey);
        if (bucket != null && bucket.size() > 0) {
            logger.debug("========rkey value=" + JSON.toJSONString(bucket));
            json.setInfo(bucket);
            return json;
        }

        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", mpid);
        wrapper.eq("state", 1);

        if (sid != null && sid.longValue() > 0) wrapper.eq("sid", sid);
        if (cid > 0) wrapper.eq("pid", cid);
        else wrapper.isNull("pid");

        if(!Strings.isNullOrEmpty(type)) wrapper.eq("type", type);
        else wrapper.andNew().ne("type", "jifen").or().isNull("type");
        wrapper.orderBy("paixu", true);

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);
        if (showCategory != null && !showCategory) {
            json.setInfo(list);
            return json;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        Wrapper<GoodsCategory> cwrapper = new EntityWrapper<GoodsCategory>();
        for (GoodsCategory item : list) {
            if (item.getHasChild() == 1) {
                cwrapper = new EntityWrapper<GoodsCategory>();
                cwrapper.eq("mpid", mpid);
                cwrapper.eq("pid", item.getId());
                cwrapper.orderBy("paixu", true);
                item.setChilds(goodscategoryService.selectList(cwrapper));
            } else {
                map.clear();
                map.put("cid", item.getId());
                map.put("skip", 0);
                map.put("limit", 6);
                item.setGoods(goodsService.getGoodsByMap(map));
            }
        }
        json.setInfo(list);
        if (cid == 0 && sid != null && sid.longValue() > 0) {
            json.setExtra(storeService.selectOne(new EntityWrapper<Store>()
                    .setSqlSelect("id,name,jianchen,pic,thumb,phone,wxno,qisongfee,peisongfee")
                    .eq("id", sid)));
        }
        if (mc.isCached()) redisService.set(rkey, bucket);// 商家类目少 全部缓存到redis
        return json;
    }

    /*
     * 电商平台版各商家商品目录查询
     * showCategory:是否展示二级子目录
     */
    @RequestMapping("/api/goods/category/mchlist")
    @ResponseBody
    public Jinfo mchlist(@RequestParam(value = "cid", required = false) int cid,
                         @RequestParam(value = "showCategory", required = false) Boolean showCategory) {

        Jinfo json = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long sid = ObjectUtil.getSid();
        if (sid == null) {
            json.setCode(1);
            json.setMsg("请求参数有误");
            return json;
        }

        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        wrapper.eq("sid", sid);
        wrapper.eq("state", 1);

        if (cid > 0) wrapper.eq("pid", cid);
        else wrapper.isNull("pid");
        wrapper.orderBy("paixu", true);

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);
        List<GoodsCategory> childs = null;
        logger.debug(">>>showCategory=" + showCategory);
        if (showCategory != null && !showCategory) {
            json.setInfo(list);
            return json;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        Wrapper<GoodsCategory> cwrapper = new EntityWrapper<GoodsCategory>();
        for (GoodsCategory item : list) {
            if (item.getHasChild() == 1) {
                cwrapper = new EntityWrapper<GoodsCategory>();
                cwrapper.eq("pid", item.getId());
                cwrapper.orderBy("paixu", true);
                item.setChilds(goodscategoryService.selectList(cwrapper));
            } else {
                map.clear();
                map.put("cid", item.getId());
                map.put("skip", 0);
                map.put("limit", 6);
                item.setGoods(goodsService.getGoodsByMap(map));
            }
        }
        json.setInfo(list);
//        json.setExtra(storeService.selectById(sid));

        return json;
    }

    /*
     * 电商平台版各商家商品目录查询
     * 返回该商家所属类目
     * 包含所有一级二级目录都返回
     */
    @RequestMapping("/api/goods/category/alllist")
    @ResponseBody
    public Jinfo alllist() {

        Jinfo json = new Jinfo();
        Long sid = ObjectUtil.getSid();
        if (sid == null) {
            json.setCode(1);
            json.setMsg("请求参数有误");
            return json;
        }

        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        wrapper.eq("sid", sid);
        wrapper.eq("isdeleted", -1);
        wrapper.eq("level", 1);

        wrapper.orderBy("paixu", true);

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);

        Wrapper<GoodsCategory> cwrapper = null;
        for (GoodsCategory item : list) {
            cwrapper = new EntityWrapper<GoodsCategory>();
            cwrapper.eq("pid", item.getId());
            cwrapper.eq("isdeleted", -1);
            cwrapper.orderBy("paixu", true);
            item.setChilds(goodscategoryService.selectList(cwrapper));
        }
        json.setInfo(list);

        return json;
    }

    @RequestMapping("/api/goodscategory/leaflist")
    @ResponseBody
    public Jinfo leaflist() {

        Jinfo json = new Jinfo();

        // 商家类目,全目录 使用缓存到redis
        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        wrapper.eq("state", 1);
        if(ObjectUtil.getSid()!=null){
            wrapper.eq("sid", ObjectUtil.getSid());
        }

        wrapper.isNull("pid");
        wrapper.orderBy("paixu", true);

        List<GoodsCategory> result = new ArrayList<GoodsCategory>();

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);
        for (GoodsCategory item : list) {
            if (item.getHasChild() == 1) {
                Wrapper<GoodsCategory> nwrapper = new EntityWrapper<GoodsCategory>();
                nwrapper.eq("mpid", ObjectUtil.getMpid());
                nwrapper.eq("state", 1);

                nwrapper.eq("pid", item.getId());
                nwrapper.orderBy("paixu", true);

                List<GoodsCategory> childs = goodscategoryService.selectList(nwrapper);
                for (GoodsCategory child : childs) {
                    GoodsCategory gc = new GoodsCategory();
                    gc.setName(item.getName() + ">" + child.getName());
                    gc.setId(child.getId());
                    result.add(gc);
                }
            } else {
                GoodsCategory gc = new GoodsCategory();
                gc.setName(item.getName());
                gc.setId(item.getId());
                result.add(gc);
            }
        }
        json.setInfo(result);

        return json;
    }

    @RequestMapping("/api/goodscategory/add")
    @ResponseBody
    public Jinfo addrAdd(GoodsCategory bean, HttpServletRequest req) {
        Jinfo json = new Jinfo();

        try {
            bean.setCreatetime(new Date());
            bean.setUid(ObjectUtil.getUid());
            bean.setMid(ObjectUtil.getMid());
            bean.setMpid(ObjectUtil.getMpid());
            bean.setSid(ObjectUtil.getSid());
            int paixun = 1;
            int level = 1;
            Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>()
                    .eq("state", 1).eq("mid", ObjectUtil.getMid()).eq("mpid", ObjectUtil.getMpid());

            if (bean.getPid() != null && bean.getPid() > 0) {
                GoodsCategory pgc = goodscategoryService.selectById(bean.getPid());
                if (pgc != null) {
                    level = pgc.getLevel() + 1;
                    wrapper.eq("level", level + 1);
                }
            }

            paixun = goodscategoryService.selectCount(wrapper) + 1;

            bean.setLevel(level);
            bean.setPaixu(paixun);


            bean.insert();
            //更新资源文件
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("GoodsCategory@" + bean.getId() + "@insert", ActorRef.noSender());
        } catch (Exception e) {
            logger.error("======api/goodscategory/add error", e);
            json.setCode(5);
        }

        return json;
    }

    @RequestMapping("/api/goodscategory/list")
    @ResponseBody
    public Jinfo gclist() {
        Jinfo json = new Jinfo();

        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        wrapper.eq("state", 1);
        wrapper.orderBy("level", true).orderBy("paixu", true);

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);
        json.setInfo(list);

        return json;
    }

    @RequestMapping("/api/goodscategory/mchlist")
    @ResponseBody
    public Jinfo mchlist(Long sid) {
        Jinfo json = new Jinfo();
        if (sid == null) sid = ObjectUtil.getSid();
        Wrapper<GoodsCategory> wrapper = new EntityWrapper<GoodsCategory>();
        wrapper.eq("mpid", ObjectUtil.getMpid());
        wrapper.eq("state", 1);
        wrapper.eq("sid", sid);
        wrapper.orderBy("level", true).orderBy("paixu", true);

        List<GoodsCategory> list = goodscategoryService.selectList(wrapper);
        json.setInfo(list);

        return json;
    }

    @RequestMapping("/api/goodscategory/modify")
    @ResponseBody
    public Jinfo addrUpdate(@Valid GoodsCategory bean, HttpServletRequest req) {
        Jinfo json = new Jinfo();
        // 字段校验
        try {
            bean.setModifytime(new Date());
            bean.updateById();
            //更新资源文件
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("GoodsCategory@" + bean.getId() + "@update", ActorRef.noSender());
        } catch (Exception e) {
            logger.error("======api/goodscategory/add error for goodscategory="+ JSON.toJSONString(bean), e);
            json.setCode(5);
        }
        return json;
    }

    @RequestMapping("/api/goodscategory/modifyall")
    @ResponseBody
    public Jinfo addrUpdateall(GoodsCategory goodscategory, String liststr) {
        Jinfo json = new Jinfo();
        logger.debug("-------------------------------api/goodscategory/modifyall liststr=", liststr);
        if (goodscategory.getId() == null || Strings.isNullOrEmpty(goodscategory.getName())) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }
        GoodsCategory category = goodscategory.selectById(goodscategory.getId());
        if (goodscategory.getId() == null) {
            json.setCode(1);
            json.setMsg("对应一级分类不存在");
            return json;
        }
        if (!category.getName().equals(goodscategory.getName())) {
            goodscategory.setModifytime(new Date());
            goodscategory.setModifier(ObjectUtil.getMpid());
            if (goodscategory.getSid() == null) goodscategory.setSid(ObjectUtil.getSid());
        }

        Wrapper<GoodsCategory> nwrapper = new EntityWrapper<GoodsCategory>();
        nwrapper.eq("state", 1);
        nwrapper.eq("isdeleted", -1);
        nwrapper.eq("pid", category.getId());

        List<GoodsCategory> childs = goodscategory.selectList(nwrapper);
        Map<String, GoodsCategory> map = new HashMap<String, GoodsCategory>();
        logger.debug("-------------------------------api/goodscategory/modifyall childs="+ JSON.toJSONString(childs));

        for (GoodsCategory item : childs) {
            map.put("fenlei" + item.getId(), item);
        }
        if (!Strings.isNullOrEmpty(liststr)) {
            List<GoodsCategory> categorylist = JSON.parseArray(liststr, GoodsCategory.class);
            if (categorylist != null && categorylist.size() > 0) {
                for (int i = 0; i < categorylist.size(); i++) {
                    GoodsCategory item = categorylist.get(i);
                    logger.debug("-------------------------------api/goodscategory/modifyall item="+ JSON.toJSONString(item));
                    logger.debug("-------------------------------api/goodscategory/modifyall map get key="+ JSON.toJSONString(map.get("fenlei" + item.getId())));
                    //新增二级分类
                    if (item.getId() == null) {
                        item.setCreatetime(new Date());
                        item.setUid(ObjectUtil.getUid());
                        item.setMid(ObjectUtil.getMid());
                        item.setMpid(ObjectUtil.getMpid());
                        item.setPaixu(childs.size() + i + 1);
                        if (item.getSid() == null) item.setSid(ObjectUtil.getSid());
                        item.insert();
                    }
                    else if (map.get("fenlei" + item.getId())!=null) {
                        if (!item.getName().equals(map.get("fenlei" + item.getId()).getName())) {
    //                        修改二级分类
                            item.setModifytime(new Date());
                            item.setModifier(ObjectUtil.getMpid());
                            if (item.getSid() == null) item.setSid(ObjectUtil.getSid());
                            item.updateById();
                        }
                        map.remove("fenlei" + item.getId());
                    }
                }

                Set<String> keys = map.keySet();
                for (String key : keys) {
                    GoodsCategory citem = map.get(key);
                    citem.setState(-1);
                    citem.setIsdeleted(1);
                    citem.setModifier(ObjectUtil.getUid());
                    citem.setModifytime(new Date());
                    citem.updateById();
                }
                goodscategory.setHasChild(1);
            }
        }

        goodscategory.insertOrUpdate();

        return json;
    }

    @RequestMapping("/api/goodscategory/delete")
    @ResponseBody
    public Jinfo categoryDelete(long cid,
                                HttpServletRequest req) {
        Jinfo info = new Jinfo();
        User user = redisService.getUser();
        if (user.getIsAdmin() != 1 && user.getIsPlatform() != 1 && user.getIsMch() != 1) {
            info.setCode(1);
            info.setMsg("当前用户无权限操作");
            return info;
        }

        GoodsCategory leimu = goodscategoryService.selectById(cid);
        if (leimu == null) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        if (leimu.getSid() != null &&
                (ObjectUtil.getSid() == null || ObjectUtil.getSid().longValue() != leimu.getSid())) {
            info.setCode(1);
            info.setMsg("非法操作");
            return info;
        }
        leimu.deleteById();

        return info;
    }

    @RequestMapping("/api/goodscategory/detail")
    @ResponseBody
    public Jinfo getGoodsCategoryDetailById(@RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo json = new Jinfo();
        try {
            GoodsCategory goodscategory = goodscategoryService.selectById(id);
            json.setInfo(goodscategory);
        } catch (Exception e) {
            logger.error("======api/goodscategory/add error", e);
            json.setCode(5);
        }
        return json;
    }
}
